#include <stdafx.h>
#include "MaterialProjectXmlSerialiser.h"
#include "MaterialProject.h"


namespace Lit
{
	namespace Editor
	{
		namespace Material
		{
			ProjectXmlSerialiser::ProjectXmlSerialiser( )
				: XmlSerialiser( "", String(PROJECT_VERSION_MAJOR)(PROJECT_VERSION_MINOR)(".")(PROJECT_VERSION_BUILD).to<float>() )
			{}
			ProjectXmlSerialiser::~ProjectXmlSerialiser()
			{}
			void ProjectXmlSerialiser::loadObject( TiXmlDocument * pDoc, const std::string &base_dir, Project& in )
			{
				TiXmlElement * project = pDoc->FirstChildElement("project");
				if( project )
				{
					std::string name(project->Attribute("name"));
					std::string type(project->Attribute("type"));
					in.newProject( name, false, false );
					TiXmlElement * file = project->FirstChildElement("file");
					for( file; file; file = file->NextSiblingElement() )
					{
						std::string fname(file->Attribute("name"));
						if( !fname.empty() )
						{
							TiXmlElement * contente = file->FirstChildElement("content");
							std::string content;
							if( contente  && !contente->NoChildren() )
							{
								TiXmlText * t = (TiXmlText*)contente->FirstChild();
								if( t ) content = t->Value();
							}

							ProjectFilePtr f;
							try{
								f = in.openFile( fname );
								Ogre::LogManager::getSingleton().logMessage("Loading '"+fname+"' from existing file text:\r\n" + f->getText());
							}
							catch(...){
								Ogre::LogManager::getSingleton().logMessage("Loading '"+fname+"' from project file"); 
								f=in.createFile( fname );
								f->setText( content );
							}
							f->save();
						}
					}
				}
			}
			void ProjectXmlSerialiser::saveObject( TiXmlDocument * pDoc, const Project& in )
			{
				TiXmlElement * root( new TiXmlElement( "project" ) );
				root->SetAttribute("name", in.getName().c_str() );
				root->SetAttribute("type", "" );

				for( auto i=in.mFiles.begin(); i!=in.mFiles.end(); i++ )
				{
					TiXmlElement * file( new TiXmlElement("file") );
					file->SetAttribute("name", i->second->getName().c_str());
						TiXmlElement * cont = new TiXmlElement("content");
						cont->LinkEndChild( new TiXmlText( i->second->getText().c_str() ) );
					file->LinkEndChild( cont );
					
					root->LinkEndChild( file );
				}
				pDoc->LinkEndChild( root );
			}
		};
	};
};